﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
using System.Text;

namespace Common.Model
{
    public class Help
    {

        public static string GuId()
        {
            return Guid.NewGuid().ToString().Replace("-", "").ToLower();
        }

        /// <summary>
        ///  时间戳转本地时间-时间戳精确到秒
        /// </summary> 
        public static DateTime ToLocalTimeDateBySeconds(long unix)
        {
            var dto = DateTimeOffset.FromUnixTimeSeconds(unix);
            return dto.ToLocalTime().DateTime;
        }

        /// <summary>
        ///  时间转时间戳Unix-时间戳精确到秒
        /// </summary> 
        public static long ToUnixTimestampBySeconds(DateTime dt)
        {
            DateTimeOffset dto = new DateTimeOffset(dt);
            return dto.ToUnixTimeSeconds();
        }


        /// <summary>
        ///  时间戳转本地时间-时间戳精确到毫秒
        /// </summary> 
        public static DateTime ToLocalTimeDateByMilliseconds(long unix)
        {
            var dto = DateTimeOffset.FromUnixTimeMilliseconds(unix);
            return dto.ToLocalTime().DateTime;
        }

        /// <summary>
        ///  时间转时间戳Unix-时间戳精确到毫秒
        /// </summary> 
        public static long ToUnixTimestampByMilliseconds(DateTime dt)
        {
            DateTimeOffset dto = new DateTimeOffset(dt);
            return dto.ToUnixTimeMilliseconds();
        }


        /// <summary>
        /// 适用于没有新建实体之间
        /// </summary>
        public static T ConvertToMap<T, S>(T t, S s)
        {
            var originalObj = s.GetType();
            var targetObj = typeof(T);
            foreach (PropertyInfo sp in originalObj.GetProperties())
            {
                

                foreach (PropertyInfo dp in targetObj.GetProperties())
                {
                    var not = dp.GetCustomAttributes(typeof(NotMappedAttribute), false);
                    if (not.Length > 0)
                    {
                        continue;
                    }

                    if (dp.Name == sp.Name && dp.CanWrite)
                    {
                        var value = sp.GetValue(s, null);

                        if (!dp.PropertyType.IsGenericType)
                        {
                            dp.SetValue(t, Convert.ChangeType(value, dp.PropertyType), null);
                        }
                        else
                        {
                            Type genericTypeDefinition = dp.PropertyType.GetGenericTypeDefinition();
                            if (genericTypeDefinition == typeof(Nullable<>))
                            {
                                dp.SetValue(t, value == null ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(dp.PropertyType)), null);
                            }
                        }
                    }
                }
            }
            return t;
        }

    }
}
